package main.java.indi.zyj.coderecord;

import java.util.ArrayList;
import java.util.List;

public class CanVisitAllRooms {

    static boolean[] visited;

    public static void main(String[] args) {
        List<List<Integer>> rooms = new ArrayList<>();
        ArrayList<Integer> list1 = new ArrayList<>();   list1.add(1);
        ArrayList<Integer> list2 = new ArrayList<>();   list2.add(2);
        ArrayList<Integer> list3 = new ArrayList<>();   list3.add(3);
        ArrayList<Integer> list4 = new ArrayList<>();
        rooms.add(list1);
        rooms.add(list2);
        rooms.add(list3);
        rooms.add(list4);
        canVisitAllRooms(rooms);
    }

    public static boolean canVisitAllRooms(List<List<Integer>> rooms) {

        visited = new boolean[rooms.size()];
        visited[0] = true;

        dfs(rooms, 0);

        for (int i = 0; i < rooms.size(); i++) {
            if (!visited[i]) {
                return false;
            }
        }

        return true;
    }

    private static void dfs(List<List<Integer>> rooms, int i) {
        List<Integer> curList = rooms.get(i);
        for (int j = 0; j < curList.size(); j++) {
            Integer index = curList.get(j);
            if (!visited[index]) {
                visited[index] = true;
                dfs(rooms, index);
            }
        }
    }

}
